import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { PageHeader, Descriptions, Space } from "antd";
import axios from "axios";
import dayjs from "dayjs";
import { HeartTwoTone, HeartFilled } from "@ant-design/icons";

export default function Detail() {
  const [content, setContent] = useState(null);
  const params = useParams();

  useEffect(() => {
    const fetchDate = async () => {
      const { data } = await axios.get(
        `/news/${params.id}?_expand=category&_expand=role`
      );
      setContent(data);
      await axios.patch(`/news/${params.id}`, {
        view: data.view + 1,
      });
    };
    fetchDate();
  }, [params.id]);

  const [isLike, setIsLike] = useState(false);
  const handelStar = async () => {
    const star = isLike ? content.star - 1 : content.star + 1;
    await axios.patch(`/news/${params.id}`, {
      star,
    });
    setContent({
      ...content,
      star,
    });
    setIsLike(!isLike);
  };

  return (
    <>
      {content && (
        <>
          <PageHeader
            onBack={() => window.history.back()}
            title={content.title}
            subTitle={
              <Space>
                <span>content.category.title</span>
                {isLike ? (
                  <HeartFilled
                    style={{ color: "#eb2f96" }}
                    onClick={handelStar}
                  />
                ) : (
                  <HeartTwoTone twoToneColor="#eb2f96" onClick={handelStar} />
                )}
              </Space>
            }
          >
            <Descriptions size="small" column={3}>
              <Descriptions.Item label="创建者">
                {content.author}
              </Descriptions.Item>
              <Descriptions.Item label="发布时间">
                {content.publishTime
                  ? dayjs(content.publishTime).format("YYYY-MM-DD HH:mm:ss")
                  : "--"}
              </Descriptions.Item>
              <Descriptions.Item label="区域">
                {content.region}
              </Descriptions.Item>
              <Descriptions.Item label="访问数量">
                {content.view}
              </Descriptions.Item>
              <Descriptions.Item label="点赞数量">
                {content.star}
              </Descriptions.Item>
              <Descriptions.Item label="评论数量">0</Descriptions.Item>
            </Descriptions>
          </PageHeader>
          <div
            style={{
              margin: "0 24px",
              paddingTop: "10px",
              borderTop: "1px solid #ccc",
            }}
            dangerouslySetInnerHTML={{ __html: content.content }}
          ></div>
        </>
      )}
    </>
  );
}
